#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import re
import sys
import time
import traceback
import win32con
import win32evtlog
import win32evtlogutil
import winerror
import local_storage

import win32security  # To translate NT Sids to account names.
server_log = {'System': [], 'Application': [], 'Security': []}


def getAllEvents(server, logtypes):
    """
    """
    local_time = int(time.time())
    for logtype in logtypes:
        try:
            data = getEventLogs(server, logtype)
            server_log[logtype] = data
        except Exception:
            pass
    local_storage.write('read_log_time', local_time)
    return server_log

def getEventLogs(server, logtype):
    """
    Get the event logs from the specified machine according to the
    logtype (Example: Application) and save it to the appropriately
    named log file
    """
    event_log = []
    try:
        read_log_time = local_storage.read('read_log_time')
    except:
        read_log_time = int(time.time())
    # read_log_time = 1542361653
    print "Logging %s events" % logtype

    hand = win32evtlog.OpenEventLog(server, logtype)
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    # print "Total events in %s = %s" % (logtype, total)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    events = win32evtlog.ReadEventLog(hand, flags, 0)
    evt_dict = {win32con.EVENTLOG_AUDIT_FAILURE: 'EVENTLOG_AUDIT_FAILURE',
                win32con.EVENTLOG_AUDIT_SUCCESS: 'EVENTLOG_AUDIT_SUCCESS',
                win32con.EVENTLOG_INFORMATION_TYPE: 'EVENTLOG_INFORMATION_TYPE',
                win32con.EVENTLOG_WARNING_TYPE: 'EVENTLOG_WARNING_TYPE',
                win32con.EVENTLOG_ERROR_TYPE: 'EVENTLOG_ERROR_TYPE'}

    try:
        events = 1
        while events:
            events = win32evtlog.ReadEventLog(hand, flags, 0)

            for ev_obj in events:
                the_time = ev_obj.TimeGenerated.Format()  # '12/23/99 15:54:09'
                sub = re.findall('(\d+)\s',the_time)[0]
                sub_time = time.strptime(re.sub('\d+\s','20%s '%sub,the_time),"%m/%d/%Y %H:%M:%S")
                timestamp = int(time.mktime(sub_time))
                if timestamp > read_log_time:
                    evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID))
                    computer = str(ev_obj.ComputerName)
                    cat = ev_obj.EventCategory
                    ##        seconds=date2sec(the_time)
                    record = ev_obj.RecordNumber
                    msg = win32evtlogutil.SafeFormatMessage(ev_obj, logtype)

                    source = str(ev_obj.SourceName)
                    if not ev_obj.EventType in evt_dict.keys():
                        evt_type = "unknown"
                    else:
                        evt_type = str(evt_dict[ev_obj.EventType])
                    log_dict = {'event_time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp)),
                                'event_id': evt_id,
                                'event_type': evt_type,
                                'event_record': record,
                                'event_source': source,
                                'event_msg': msg}

                    event_log.append(log_dict)

    except:
        print traceback.print_exc(sys.exc_info())

    return event_log


def get_server_log():
    try:
        server = None  # None = local machine
        logTypes = ["System", "Application", "Security"]
        logs = getAllEvents(server, logTypes)
        for k in logs:
            if logs[k]:
                return logs
        return
    except Exception as e:
        print e


if __name__ == "__main__":
    try:
        server = None  # None = local machine
        logTypes = ["System", "Application", "Security"]
        getAllEvents(server, logTypes)
    except Exception as e:
        pass
        # print e
        # raw_input('error!!!!!!')